﻿package com.neriksworkshop.lib.colourLovers.items
{
	import com.neriksworkshop.lib.colourLovers.core.AbstractGraphicItem;
	import com.neriksworkshop.lib.colourLovers.events.GraphicItemEvent;
	import com.neriksworkshop.lib.colourLovers.params.Params;
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.geom.Rectangle;
	import flash.net.URLRequest;

	
	/**
	 * ...
	 * @author ...
	 */
	public class Pattern extends AbstractGraphicItem implements IGraphicItem
	{
		//from colourlovers api
		private var _colors:/*String*/Array = new Array();
		
		//computed
		private var _colorItems:/*Colour*/Array = new Array();
		
		
		private var _l:Loader;
		private var _d:Rectangle;
		
		private var _csCalled:Boolean;
		
		
		public function Pattern() 
		{
			super(this);
		}
		
		override public function buildFromData(data:*):void
		{
			var dataFinal:* = (data is String) ? XML(data) : data;
			
			super.buildFromData(dataFinal);
			
			_colors = new Array();
			var colorsData:* = (dataFinal is XML) ? dataFinal.colors.hex : dataFinal.colors;
			
			for each (var colorItem:* in colorsData) _colors.push(colorItem)
								
			buildColourItems();			
			
		}
		
		/*public override function buildFromXML(xmlData:XML):void
		{
			super.buildFromXML(xmlData);
			_colors = new Array();
			
			for each (var colorXML:XML in xmlData.colors.hex) 
			{
				_colors.push(colorXML)
			}
								
			buildColourItems();
			
		}*/
		
		
		public override function createSprite(dimensions:Rectangle = null):Sprite
		{
			_csCalled = true;
			if (!dimensions) var dimensions:Rectangle = Params.DEFAULT_DIMENSIONS;
			
			_sp = new Sprite();
			
			_d = dimensions;
			
			_l = new Loader();
			_l.contentLoaderInfo.addEventListener(Event.COMPLETE, onImageLoaded);
			_l.load(new URLRequest(imageUrl));
			
			return _sp;
		}
		
		private function onImageLoaded(e:Event):void 
		{
			//trace('loaded', _sp);
			var bmd:BitmapData = Bitmap(_l.content).bitmapData;
			
			
			_sp.graphics.beginBitmapFill(bmd, null, true, true);
			//_sp.graphics.beginFill(0xff0000);
			_sp.graphics.drawRect(_d.x, _d.y, _d.width, _d.height);
						
			dispatchEvent(new GraphicItemEvent(GraphicItemEvent.IMAGE_LOADED));

		}
		
		
		public function get colors():Array  							{ 	return _colors;  }
		
		public function get colorItems():/*Color*/Array 				{ 	return _colorItems; }
		
		

		

		
		private function buildColourItems():void
		{
			_colorItems = new Array();
			
			for each (var color:String in colors) 
			{
				_colorItems.push(new Color(Number('0x'+color)));
			}
		}	
		
		
		
	}
	
	
	
}